<template>
  <BasicModal v-bind="$attrs" @register="register" :title="getTitle" width="70%" >
        <a-spin :spinning="loading" size="large" tip="Loading...">
          <a-form ref="report" class="antd-modal-form">
            <p style="text-align: center">
              <span style="width: 35%; text-align: center; font: 1.7em sans-serif">{{
                formData.labItemsReportPage.samName }}</span>
              <span style="width: 35%; text-align: center; font: 1.7em sans-serif">检验结果报告单</span>
            </p>
            <table id="items" cellspacing="1" style="width: 100%; height: 150px; border: 1px solid #a8aeb2">
              <tr class="tr">
                <th class="thC">依据标准:</th>
                <th class="thE" :colspan="3">{{ formData.labItemsReportPage.basisName }}</th>
              </tr>
              <tr class="tr">
                <th class="thC">样品编号:</th>
                <td class="thE">{{ formData.labItemsReportPage.samNum }}</td>
                <td class="thC">报告编号:</td>
                <td class="thE">{{ formData.labItemsReportPage.reportNum }}</td>
              </tr>
              <tr class="tr">
                <th class="thC">填报日期:</th>
                <td class="thE">{{ formData.labItemsReportPage.reportDate }}</td>
                <td class="thC"></td>
                <td class="thE"></td>
              </tr>
            </table>
            <!--项目列表-->
            <labItemsTable ref="registerItemsTable" :labEntrustItemsList="formData.labItemsReportPage.labEntrustItemsIndexPageList"></labItemsTable>
            <table id="items" cellspacing="1" style="width: 100%; height: 250px; border: 1px solid #a8aeb2">
              <tr class="tr">
                <th class="thB">检验结论</th>
                <th style="text-align: left; border: 1px solid #a8aeb2; font: 1.1em sans-serif" colspan="5">
                  <a-textarea v-model:value="formData.labItemsReportPage.reportConcl" size="large" class="input" />
                </th>
              </tr>
              <tr class="tr">
                <th class="thB">备注</th>
                <th style="text-align: left; border: 1px solid #a8aeb2; font: 1.1em sans-serif" colspan="5">
                  <a-textarea v-model:value="formData.labItemsReportPage.remark" size="large" class="input" />
                </th>
              </tr>
              <tr style="height: 30px; border: 1px solid #a8aeb2">
                <th class="thB">批准人</th>
                <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif">
                  {{ formData.labItemsReportPage.ratifyName }}</th>
                <th class="thB">审核人</th>
                <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif">
                  {{ formData.labItemsReportPage.auditName }}</th>
                <th class="thB">主检人</th>
                <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif">
                  {{ formData.labItemsReportPage.checkName }}</th>
              </tr>
            </table>
          </a-form>
        </a-spin>
    <template v-slot:footer>
      <a-button type="default" @click="closeModal">关闭</a-button>
      <a-button type="primary" @click="previewReport">报告预览</a-button>
      <a-button type="danger" @click="auditModal('no')">不同意</a-button>
      <a-button type="primary" @click="auditModal('yes')">同意</a-button>
    </template>
    <div style="display: none">
      <iframe id="pdfPreviewIframe" :src="url" frameborder="0" width="100%" height="550px" scrolling="auto"></iframe>
    </div>
  </BasicModal>
  <PdfViewer v-if="openPdf" :pdfUrl="jsPdf" @closePdf="closePdf"></PdfViewer>
</template>

<script lang="ts" setup>
import { BasicModal, useModalInner } from '/@/components/Modal';
import { ref, reactive } from 'vue';
import labItemsTable from './LabCheckItemsTable.vue';
import { getReportReviewData, auditReportData } from './LabItemReportList.api';
import { Modal } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/src/hooks/web/useMessage';
import PdfViewer from './subTables/pdfViewer.vue';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';
const { createMessage } = useMessage();

const globSetting = useGlobSetting();
const baseApiUrl = globSetting.domainUrl;
let openPdf = ref(false);
let jsPdf = ref("");
const url = ref(`${baseApiUrl}/sys/common/pdf/pdfPreviewIframe`);



const emit = defineEmits(['success']);
const loading = ref(true);
const result = ref(true);
const report = ref(false);
const getTitle = ref('检验结果报告');
const { userInfo } = useUserStore();
const i = ref(0);
const auditDisable = ref(true)
let receiveParams = {};
const formData = reactive<Record<string, any>>({
  labItemsReportPage: [
    {
      id: '',
      samName: '',
      samNum: '',
      basisName: '',
      basisNum: '',
      reportNum: '',
      reportDate: null,
      reportConcl: '',
      remark: '',
      taskId: '',
      checkId: '',
      checkName: '',
      auditId: '',
      auditName: '',
      ratifyId: '',
      ratifyName: '',
      billStatus: '',
      labEntrustItemsList: [],
    },
  ],
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({
    minHeight: 400,
    useWrapper: true,
    centered: true,
    wrapperFooterOffset: 5,
  });
  formData.entrustType = data.record.entrustType;
  receiveParams = {
    entrustType: data.record.entrustType,
    reportCode: data.record.reportCode,
    userName: userInfo.realname,
  };
  let params = {
    entrustId: data.record.id,
  };
  i.value = 0;
  await getReportReviewData(params)
    .then((res) => {
      let itemNameOrder = new Map();
      res.labItemsReportPage.labEntrustItemsIndexPageList.forEach((item, index) => {
        itemNameOrder.set(item.itemName, index);
      });
      // console.log('数据',res)
      jsPdf.value = `${baseApiUrl}/sys/common/static${res.labItemsReportPage.pfdFile}`;
      // console.log('jsPdf.value',jsPdf.value)
      Object.assign(formData, res);
    })
    .finally(() => {
      loading.value = false;
    });
});

//报告预览
function previewReport() {
  // loading.value = true;
  // openPdf.value = true;
  // window.location.href = jsPdf.value;
  // console.log('传递给pageoffice的参数', receiveParams);
  // POBrowser.openWindow('http://10.89.208.24:9595/?param=' + JSON.stringify(receiveParams), 'fullscreen=yes', JSON.stringify(receiveParams));
  // setTimeout(() => {
  //   loading.value = false;
  // }, 5000);
  const urlArr = formData.labItemsReportPage.pfdFile.split('/');
  const title = urlArr[urlArr.length - 1];
  let encodedUrl = `${baseApiUrl}/sys/common/static${formData.labItemsReportPage.pfdFile}`;
  let iframe = document.getElementById('pdfPreviewIframe');
  let json = { title: title, token: getToken(), url: encodedUrl };
  iframe.contentWindow.postMessage(json, '*');
}
function closePdf() {
  openPdf.value = false;
}



function auditModal(data) {
  if (formData.labItemsReportPage.billStatus == '待审核') {
    if (data == 'yes') {
      let params = {
        id: formData.labItemsReportPage.id,
        billStatus: '待批准',
        entrustType: formData.entrustType,
        reportConcl: formData.labItemsReportPage.reportConcl,
        remark: formData.labItemsReportPage.remark,
      };
      Modal.confirm({
        title: '是否确认通过?',
        async onOk() {
          loading.value = true;
          //暂时屏蔽签名
          // updateSign();
          await auditReportData(params);
          closeModal();
          emit('success');
        },
      });
    } else if (data == 'no') {
      let params = {
        id: formData.labItemsReportPage.id,
        billStatus: '待编辑',
        entrustType: formData.entrustType,
        reportConcl: formData.labItemsReportPage.reportConcl,
        remark: formData.labItemsReportPage.remark,
      };
      Modal.confirm({
        title: '是否确认不通过?',
        async onOk() {
          await auditReportData(params);
          closeModal();
          emit('success');
        },
      });
    }
  } else if (formData.labItemsReportPage.billStatus == '待批准') {
    if (data == 'yes') {
      let params = {
        id: formData.labItemsReportPage.id,
        billStatus: '下载',
        entrustType: formData.entrustType,
        reportConcl: formData.labItemsReportPage.reportConcl,
        remark: formData.labItemsReportPage.remark,
      };
      Modal.confirm({
        title: '是否确认通过?',
        async onOk() {
          loading.value = true;
          //暂时屏蔽更新签名
          // updateSign();
          await auditReportData(params);
          closeModal();
          emit('success');
        },
      });
    } else if (data == 'no') {
      let params = {
        id: formData.labItemsReportPage.id,
        billStatus: '待审核',
        entrustType: formData.entrustType,
        reportConcl: formData.labItemsReportPage.reportConcl,
        remark: formData.labItemsReportPage.remark,
      };
      Modal.confirm({
        title: '是否确认不通过?',
        async onOk() {
          await auditReportData(params);
          closeModal();
          emit('success');
        },
      });
    }
  }
}
// 更新签名
function updateSign() {
  let signature = '/entrust/labEntrust/signature';
  let servestoken = '/entrust/labEntrust/serveToken';
  //获取服务token和员工票据,员工id
  defHttp.get({ url: servestoken }, { isTransformResponse: false }).then((srcs) => {
    console.log(srcs);
    //员工id
    let yaunid = srcs.cardid;
    //let yaunid = 43;
    //服务token
    let tokenServe = srcs.tokenServe;
    //let tokenServe = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1MDcyNzUxNDc0NDM0Mzc1NjgiLCJhdWQiOiJiYXNlIiwiaXNzIjoiemh1bnplIiwiZXhwIjoxNzAxMzQwNzgzLCJpYXQiOjE3MDEzMzI5ODN9.f4zHoRe2Z0lvE5HTmRQUqOmlYP9ygQhC_X8icNHhsuY";
    //员工票据
    let employeeTicket = srcs.employeeTicket;
    //let employeeTicket = "22a64aa46829dacaca9f4e10221de1b215be653d";
    //封装请求
    let datae = {
      businessCreateUserId: yaunid,
      businessCreateUserPositionId: '',
      content: 'flowlame=12',
      description: '',
      name: '12',
    };
    //调用签证
    //获取签名
    window.SCZZ_SIGN.open({
      token: employeeTicket, //员工票据，通过获取员工票据接口获取得到
      data: datae, //签证数据,用于签证校验，其内容见下文
      type: 'PERSONAL_SIGNATURE', //类型（个人签名:PERSONAL_SIGNATURE，单位签章:CORP_SIGNATURE），根据不同的类型打开对应的签证页面
      mobile: false, //移动端调用时需要传递
      call: async function (res) {
        console.log('更新签名弹窗获取结果', res);
        loading.value = false;
        if (res.code === 1000) {
          if (res.data.imageUrl) {
            // 把签名存在数据库
            let urls = signature + '?id=' + yaunid + '&paramasa=' + res.data.imageUrl;
            defHttp.post({ url: urls }, { isTransformResponse: false });
            //提交审批表单
            if (formData.labItemsReportPage.billStatus == '待审核') {
              let params = {
                id: formData.labItemsReportPage.id,
                billStatus: '待批准',
                entrustType: formData.entrustType,
                reportConcl: formData.labItemsReportPage.reportConcl,
                remark: formData.labItemsReportPage.remark,
              };
              await auditReportData(params);
              closeModal();
              emit('success');
            } else if (formData.labItemsReportPage.billStatus == '待批准') {
              let params = {
                id: formData.labItemsReportPage.id,
                billStatus: '下载',
                entrustType: formData.entrustType,
                reportConcl: formData.labItemsReportPage.reportConcl,
                remark: formData.labItemsReportPage.remark,
              };
              await auditReportData(params);
              closeModal();
              emit('success');
            }
          } else {
            createMessage.error('签名失败，请重新签名！');
          }
        }
        //回调，接收一个结果对象，该对象里包含sdk的响应状态码code，响应信息msg，当响应code为1000时有响应数据data，响应数据内容见下文
      },
    });
  });
}
</script>

<style scoped>
.header {
  line-height: 35px;
  background-color: #f2f2f2;
  color: #666;
}

.tr {
  height: 45px;
  border: 1px solid #a8aeb2;
}

.thA {
  width: 75%;
  text-align: center;
  border: 1px solid #a8aeb2;
  font: 1.1em sans-serif;
}

.thB {
  width: 15%;
  text-align: center;
  border: 1px solid #a8aeb2;
  font: 1.1em sans-serif;
}

.thC {
  width: 20%;
  text-align: center;
  border: 1px solid #a8aeb2;
  font: 1.1em sans-serif;
}

.thD {
  width: 80%;
  text-align: center;
  border: 1px solid #a8aeb2;
  font: 1.1em sans-serif;
}

.thE {
  width: 30%;
  text-align: left;
  border: 1px solid #a8aeb2;
  font: 1.1em sans-serif;
}

.input {
  width: 100%;
  height: 100%;
  border: none;
  background-color: inherit;
  outline: none;
  border-bottom: none;
  font: 1em sans-serif;
}

.container {
  display: flex;
  width: 100%;
  border: 1px;
  justify-content: center;
  max-width: 100%;
}

.box {
  width: 50%;
  border: 1px solid #a8aeb2;
  margin: 5px;
  max-height: 75vh;
  /* overflow-y: auto; */
}

:deep(.ant-spin-nested-loading) {
  height: 100%;
}

:deep(.ant-modal .ant-modal-body) {
  max-height: 75vh;
}
</style>
